// ignore_for_file: constant_identifier_names

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'auth_3rd_model.dart';

// 第三方登录管理
abstract class IAuth3rdManager {
  Future<Auth3rdModel> auth();
}

// 第三方登录异常
class AuthException extends Error {
  static const CODE_GOOGLE_NULL_ACCOUNT = -1001;
  static const CODE_GOOGLE_AUTH_ERROR = -1002;
  static const CODE_GOOGLE_SIGN_IN_ERROR = -1003;
  static const CODE_APPLE_SIGN_IN_ERROR = -1004;
  int code;
  String? message;

  AuthException(this.code, {this.message = ''});
}

// Google 第三方登录管理
class GoogleAuthManager extends IAuth3rdManager {
  GoogleSignIn? _client;

  // Google 第三方登录管理
  final String googleClientIdAndroid;
  final String googleClientIdIos;
  final String googleServiceId;

  GoogleAuthManager(
    this.googleClientIdAndroid,
    this.googleClientIdIos,
    this.googleServiceId,
  ) {
    var appKey = Platform.isAndroid ? googleClientIdAndroid : googleClientIdIos;
    _client = GoogleSignIn(
      clientId: appKey,
      serverClientId: googleServiceId,
      scopes: <String>['email', 'profile', 'openid'],
    );
  }

  @override
  Future<Auth3rdModel> auth() async {
    return _client!.signIn().then((account) async {
      if (account == null) {
        debugPrint('Google Account is null');
        throw AuthException(AuthException.CODE_GOOGLE_NULL_ACCOUNT);
      }
      await Future.delayed(const Duration(milliseconds: 100));
      return account.authentication
          .then((authentication) => Auth3rdModel(
              uid: account.id,
              token: authentication.idToken,
              email: account.email,
              avatar: account.photoUrl,
              nickName: account.displayName))
          .catchError((error) {
        debugPrint('Google Auth Error: $error');
        throw AuthException(AuthException.CODE_GOOGLE_AUTH_ERROR,
            message: error.toString());
      });
    }).catchError((error) {
      debugPrint('Google Sign In Error: $error');
      throw error is AuthException
          ? error
          : AuthException(AuthException.CODE_GOOGLE_SIGN_IN_ERROR,
              message: error.toString());
    });
  }
}

// Apple 第三方登录管理
class AppleAuthManager extends IAuth3rdManager {
  @override
  Future<Auth3rdModel> auth() {
    return SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName,
      ],
    ).then((credential) {
      return Auth3rdModel(
        uid: credential.userIdentifier,
        token: credential.identityToken,
        email: credential.email,
        name: Auth3rdName(
          familyName: credential.familyName,
          givenName: credential.givenName,
        ),
      );
    }).catchError((e) {
      debugPrint('Apple Sign In Error: $e');
      throw AuthException(AuthException.CODE_APPLE_SIGN_IN_ERROR);
    });
  }
}
